﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace SMS_Server
{
    class Action_Forward2TCP:Incoming_Action
    {
        public string ActionName;
        public string ActionFormat;
        public string[] ParamNames = null;
        public string IP;
        public int Port;
        public bool HasResponse;

        public bool GetResult(string PhoneNumber, object[] Params, out string result)
        {
            if (ActionFormat == "")
            {
                string str = "";
                foreach (string s in Params)
                {
                    if (str != "") str += " ";
                    str += s;
                }
                return GetResult(PhoneNumber, str, out result);
            }

            if (ParamNames == null)
            {
                ActionFormat = ActionFormat.Replace("[", "").Replace("]", "");
                ParamNames = ActionFormat.Split(' ');
            }
            if (Params.Length != ParamNames.Length)
            {
                string resp = "Please write in the given format " + ActionName.ToUpper();
                for (int i = 0; i < ParamNames.Length; i++)
                {
                    resp += " ";
                    resp += "[" + ParamNames[i] + "]";
                }
                result = resp; return true;
            }
            string RequestString = "PhoneNumber=" + PhoneNumber;
            for (int i = 0; i < ParamNames.Length; i++)
            {
                if (RequestString != "") RequestString += "&";
                RequestString += ParamNames[i] + "=" + Params[i];
            }

            try
            {
                TcpClient Tcp = new TcpClient();
                Tcp.Connect(IPAddress.Parse(IP), Port);
                Tcp.SendTimeout = 1000;
                Tcp.ReceiveTimeout = 1000;

                StreamWriter sw = new StreamWriter(Tcp.GetStream());
                sw.WriteLine(RequestString);
                sw.Flush();

                result = "";
                StreamReader sr = new StreamReader(Tcp.GetStream());

                result += sr.ReadLine();

                Tcp.Close();
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
                el.Log = "Application";
                el.MachineName = ".";
                el.Source = "SMS Server";
                el.WriteEntry("Error in Forward2TCP: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);

                //string comm = ActionName.ToUpper();
                //for (int i = 0; i < Params.Length; i++)
                //{
                //    comm += " ";
                //    comm += "[" + Params[i] + "]";
                //}
                result = "";
                //DataAccess DA = new DataAccess(Global.GetUsageDatabaseName(), Global.DatabasePassword);
                //DA.CommandString = "INSERT INTO ErrorList(ClassName, Args, Error, ErrorDate) VALUES (@ClassName, @Args, @Error, @ErrorDate)";
                //DA.AddParameter("@ClassName", "Forward2TCP");
                //DA.AddParameter("@Args", comm);
                //DA.AddParameter("@Error", ex.Message);
                //DA.AddParameter("@ErrorDate", DateTime.Now);
                //DA.ExecuteNonQuery();
                //DA.Close();
                return false;
            }
            return HasResponse;
        }

        public bool GetResult(string PhoneNumber, string data, out string result)
        {
            string RequestString = "PhoneNumber=" + PhoneNumber;
            RequestString += "&message=" + data;

            try
            {
                TcpClient Tcp = new TcpClient();
                Tcp.Connect(IPAddress.Parse(IP), Port);
                Tcp.SendTimeout = 1000;
                Tcp.ReceiveTimeout = 1000;

                StreamWriter sw = new StreamWriter(Tcp.GetStream());
                sw.WriteLine(RequestString);
                sw.Flush();

                result = "";
                StreamReader sr = new StreamReader(Tcp.GetStream());

                result += sr.ReadLine();

                Tcp.Close();
            }
            catch (Exception ex)
            {
                result = "";
                DataAccess DA = new DataAccess(Global.GetUsageDatabaseName(), Global.DatabasePassword);
                DA.CommandString = "INSERT INTO ErrorList(ClassName, Args, Error, ErrorDate) VALUES (@ClassName, @Args, @Error, @ErrorDate)";
                DA.AddParameter("@ClassName", "Forward2TCP");
                DA.AddParameter("@Args", "");
                DA.AddParameter("@Error", ex.Message);
                DA.AddParameter("@ErrorDate", DateTime.Now);
                DA.ExecuteNonQuery();
                DA.Close();
                return false;
            }
            return HasResponse;
        }

    }
}
